package ferri.lorenzo;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class DroidhouseMultiroomActivity extends Activity {
	/** Called when the activity is first created. */

	private static final String TAG = "UDP_SERVER";

	private String[] ipAddress = null;
	private String filePathText[] = null;
	String texts = "";
	SeekBar mSeekBar;

	private int volume = 0;
	Servercontrol[] p = new Servercontrol[10];
	Bundle contenitore;
	String[] Titolo;
	String[] Durata;
	ImageButton playbackButton;
	Chronometer mChronometer;
	TextView mTextLength;
	String delay = "5";
	int pos = 0;
	OptionsMenu optionsMenu = null;
	SeekBar seek;
	long[] albart = null;
	Context context = this; // Lista delle durate delle canzoni

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		for (int i = 0; i < 10; i++) {
			p[i] = new Servercontrol();
		}

		playbackButton = (ImageButton) findViewById(R.id.buttonStart);
		seek = (SeekBar) findViewById(R.id.SeekBar01);
		seek.setEnabled(false);
		mTextLength = (TextView) findViewById(R.id.text_length);
		mChronometer = (Chronometer) findViewById(R.id.chronometer1);
		mSeekBar = (SeekBar) findViewById(R.id.seek_progress);

		mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromTouch) {
				if (ipAddress != null)
					if (volume < progress) {
						for (int i = volume; i < progress; i++)
							increasevol();
						volume = progress;
						Log.i("Volume", "" + volume);
					} else {
						for (int i = volume; i > progress && i > 0; i--)
							decreasevol();
						volume = progress;
					}
			}

			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub

			}

			public void onStopTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub

			}

		});

		// Watch for button clicks.
		// Visualizziamo la corrispondente Dialog
		AlertDialog alertDialog = new AlertDialog.Builder(
				DroidhouseMultiroomActivity.this).create();
		alertDialog.setTitle("Rescan SD");
		alertDialog.setMessage("Hai inserito nuovi file?");
		alertDialog.setButton("Si", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

				try {
					rescanSdcard();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

		alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

				// here you can add functions

			}
		});
		alertDialog.show();

	}

	private void rescanSdcard() throws Exception {
		IntentFilter intentFilter = new IntentFilter(
				Intent.ACTION_MEDIA_SCANNER_STARTED);
		intentFilter.addDataScheme("file");
		sendBroadcast(new Intent(
				Intent.ACTION_MEDIA_MOUNTED,
				Uri.parse("file://" + Environment.getExternalStorageDirectory())));
	}

	@Override
	protected void onResume() {
		super.onResume();
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		context = this;
		for (int x = 0; x < p.length; x++)
			if (p[x].isAlive() && x != pos)
				p[x].setcurrent();

		if (p[pos].isAlive()) {
			p[pos].getdur();

			// filePathText = p[pos].getsongs();

		}

		delay = prefs.getString("delay", "5");
		TextView t = (TextView) findViewById(R.id.itemLabel);
		t.setText(delay);

	}

	// This method is called at button click because we assigned the name to the
	// "On Click property" of the button
	public void buttonStartHandler(View view) {
		switch (view.getId()) {
		case R.id.buttonStart:
			Log.d(TAG, "Starting server ....");

			if (!p[pos].isAlive() && filePathText != null && ipAddress != null) {
				Handler handler = new MyHandler();
				p[pos] = new Servercontrol(filePathText,

				ipAddress, "303" + pos, Integer.parseInt(delay), Titolo,
						Durata, handler);
				mChronometer.setBase(SystemClock.elapsedRealtime());
				p[pos].setcurrent();
				p[pos].start();
				playbackButton
						.setImageResource(R.drawable.ic_media_playback_pause);
				mChronometer.start();
			}

		}

	}

	public void buttonStopHandler(View view) {

		switch (view.getId()) {
		case R.id.stopButton:
			Log.d(TAG, "Stopping server ....");
			if (p != null)
				p[pos].stopServer();
			mChronometer.stop();
			playbackButton.setImageResource(R.drawable.ic_media_playback_start);

		}

	}

	public void increasevol() {

		for (int i = 0; i < ipAddress.length; i++)
			try {

				URL url = new URL("http://" + ipAddress[i]
						+ "/control.cgi?vol=p");
				HttpURLConnection c = (HttpURLConnection) url.openConnection();
				c.setConnectTimeout(25);
				c.setReadTimeout(1);
				c.getResponseCode();
				Log.i(TAG, "http://" + ipAddress + "/control.cgi?vol=1");
			} catch (IOException e) {

			}

	}

	public void decreasevol() {

		for (int i = 0; i < ipAddress.length; i++)
			try {

				URL url = new URL("http://" + ipAddress[i]
						+ "/control.cgi?vol=m");
				HttpURLConnection c = (HttpURLConnection) url.openConnection();
				c.setConnectTimeout(25);
				c.setReadTimeout(1);
				c.getResponseCode();
				Log.i(TAG, "http://" + ipAddress + "/control.cgi?vol=2");

			} catch (IOException e) {
				Log.i("HTTP", "richiesta fallita");
			}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Aggiungiamo il solo MenuItem con l'intent per
		// le opzioni
		super.onCreateOptionsMenu(menu);
		optionsMenu = new OptionsMenu(this, menu);
		return true;
	}

	public void Song(View view) {
		switch (view.getId()) {
		case R.id.Songs:
			Log.d(TAG, "Stopping server ....");
			Intent i = new Intent(DroidhouseMultiroomActivity.this,
					SearchSong.class);
			startActivityForResult(i, 0);

		}

	}

	public void rooms(View view) {
		switch (view.getId()) {
		case R.id.button_room:
			Intent i = new Intent(DroidhouseMultiroomActivity.this,
					DiscovererActivity.class);
			startActivityForResult(i, 1);

		}

	}

	public void forward_bacward(View view) {
		switch (view.getId()) {
		case R.id.button_skip_forward:
			p[pos].next();
			break;
		case R.id.button_skip_backward:
			p[pos].back();
			break;

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// You can use the requestCode to select between multiple child
		// activities you may have started. Here there is only one thing
		// we launch.
		if (requestCode == 0) {

			// We will be adding to our text.

			// This is a standard resultCode that is sent back if the
			// activity doesn't supply an explicit result. It will also
			// be returned if the activity failed to launch.
			if (resultCode == RESULT_CANCELED) {
				texts = ("(cancelled)");

				// Our protocol with the sending activity is that it will send
				// text in 'data' as its result.
			} else {

				if (data != null) {

					filePathText = data.getStringArrayExtra("path");
					Titolo = data.getStringArrayExtra("titolo");
					Durata = data.getStringArrayExtra("durata");
					albart = data.getLongArrayExtra("art");
					// Log.d("response", data.getStringExtra("io"));
				}
			}
		}

		if (requestCode == 1) {
			if (resultCode == RESULT_CANCELED) {
				texts = ("(cancelled)");

				// Our protocol with the sending activity is that it will send
				// text in 'data' as its result.
			} else {
				contenitore = data.getExtras();

				ipAddress = contenitore.getStringArray("allip");

				pos = contenitore.getInt("id");

			}
		}

	}

	private class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			if (bundle.containsKey("reset")) {
				mChronometer.setBase(SystemClock.elapsedRealtime());
			}
			if (bundle.containsKey("now")) {
				seek = (SeekBar) findViewById(R.id.SeekBar01);
				seek.setProgress(bundle.getInt("now"));
			}
			if (bundle.containsKey("dur")) {
				TextView t = (TextView) findViewById(R.id.textView2);
				seek.setProgress(0);
				seek.setMax(bundle.getInt("dur"));

				if (bundle.containsKey("titolo"))
					if (bundle.getString("titolo").equals("Stop")) {
						mChronometer.stop();
						playbackButton
								.setImageResource(R.drawable.ic_media_playback_start);
						seek.setProgress(0);
						TextView te = (TextView) findViewById(R.id.itemLabel);
						int j = bundle.getInt("dur");
						String ti = "" + j;
						te.setText(ti);
					} else {
						t.setText(bundle.getString("titolo"));
						int sec = (bundle.getInt("dur") / 1000) % 60;
						int min = (bundle.getInt("dur") / 1000) / 60;

						// aggiorno la TextView
						if (sec < 10) {
							mTextLength.setText(min + ":0" + sec);
						} else {
							mTextLength.setText(min + ":" + sec);
						}
					}

			}
			if (bundle.containsKey("albart")) {
				ImageView i = (ImageView) findViewById(R.id.imageView1);
				Uri baseUri = Uri
						.parse("content://media/external/audio/albumart");
				long albumId = albart[(int) bundle.getFloat("albart")];
				Uri artworkUri = ContentUris.withAppendedId(baseUri, albumId);
				if (artworkUri != null) {
					ParcelFileDescriptor fd = null;
					try {
						ContentResolver cr = context.getContentResolver();
						fd = cr.openFileDescriptor(artworkUri, "r");
						Bitmap b = BitmapFactory.decodeFileDescriptor(fd
								.getFileDescriptor());
						i.setImageBitmap(b);
					} catch (FileNotFoundException e) {
						i.setImageResource(R.drawable.ic_album);
					} finally {
						try {
							if (fd != null) {
								fd.close();
							}
						} catch (IOException e) {
						}
					}
				}
			}

		}
	}

	// Intercettazione del tasto back
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		Log.d(TAG, "inside onBackPressed()");
		onRetainNonConfigurationInstance();
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			//
			AlertDialog alertDialog = new AlertDialog.Builder(
					DroidhouseMultiroomActivity.this).create();
			alertDialog.setTitle("Chiusura player");
			alertDialog
					.setMessage("Uscire la riproduzioni saranno interrotte(premere il tasto home per mantenere la riproduzione attiva)?");
			alertDialog.setButton("Si", new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					
					//Close the application 
					finish();

				}
			});

			alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

					// here you can add functions

				}
			});
			
			alertDialog.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);

	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		optionsMenu.onPrepareOptionsMenu(menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean result = optionsMenu.onOptionsItemSelected(item);
		return result;
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}